<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace plugins\dingding\lib;

use think\Db;
use think\db\Query;

class Dingding
{
    private $appid;
    private $corp;
    private $app;
    private $access_token;
    private $agentid;
    private $appkey;
    private $appsecret;
    private $corpid;
    private $jsticket;
    private $admin;

    function __construct($corp,$app){
        $this->corp = $corp;
        $this->app = $app;
        $appinfo = Db::name('plugin_dingding_app')->where(["app"=>$app,"corp"=>$corp])->find();
        if($appinfo){
            $this->appid = $appinfo['id'];
            $this->corpid = $appinfo['corpid'];
            $this->agentid = $appinfo["agentid"];
            $this->appkey = $appinfo["appkey"];
            $this->appsecret = $appinfo["appsecret"];
            $this->admin = $appinfo['admin'];
        }
        else return null;
    }
    protected function initialize($needjs = false)
    {
        // 监听home_init
        require_once("../vendor/dingding/TopSdk.php");

        $configname = "dingding_" . $this->appid;

        $access_token = config($configname .'.access_token');
        $actk_time = config($configname .'.lasttime');
        $nowtime = time();
        if($actk_time) {
            if($nowtime-$actk_time<7200)  $timeout = false;
            else $timeout = true;
        }
        if(empty($access_token)||empty($actk_time) || $timeout){
            $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET , \DingTalkConstant::$FORMAT_JSON);
            $req = new \OapiGettokenRequest;
            $req->setAppkey($this->appkey);
            $req->setAppsecret($this->appsecret);

            $resp=$c->execute($req, "accessToken","https://oapi.dingtalk.com/gettoken");
            //print_r($resp);
            $access_token = $resp->access_token;

            cmf_set_dynamic_config([$configname => ['access_token' => $access_token,'actk_time'=>$nowtime]]);
        }
        $this->access_token = $access_token;
        if($needjs){
            $jsticket = config($configname .'.jsticket');
            $jstk_time = config($configname .'.jstktime');
            $nowtime = time();
            if($jstk_time) {
                if ($nowtime - $jstk_time < 7200) $timeout = false;
                else $timeout = true;
            }
            if(empty($jsticket)||empty($jstk_time) || $timeout){
                $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET , \DingTalkConstant::$FORMAT_JSON);
                $req = new \OapiGetJsapiTicketRequest();
                $resp=$c->execute($req, $this->access_token,"https://oapi.dingtalk.com/get_jsapi_ticket");
                $jsticket = $resp->ticket;

                cmf_set_dynamic_config([$configname => ['jsticket' => $jsticket,'jstk_time'=>$nowtime]]);
            }
            $this->jsticket = $jsticket;
            }
    }
    public function getAdmin(){
        return $this->admin;
    }
    public function getAppid(){
        return $this->appid;
    }
    public function getCorpid(){
        return $this->corpid;
    }
    public function getAccessToken(){
        $this->initialize();
        return $this->access_token;
    }
    public function getAgentid(){
        return $this->agentid;
    }

    public function getAppkey(){
        return $this->appkey;
    }

    public function getAppsecret(){
        return $this->appsecret;
    }

    public function getTicket()
    {
        $this->initialize(true);
        return $this->jsticket;
    }

    public function getJsddconfig(){
        //$this->initialize();
        $agentId = $this->agentid;
        $corpId = $this->corpid;
        $nonceStr = 'abcdefg';
        $timeStamp = time();
        $url = $this->curPageURL();
//        $url = 'http://xinchan.cmttfj.com/upinfo/admin_send/index';
        $ticket = $this->getTicket();
        $signature = $this->sign($ticket, $nonceStr, $timeStamp, $url);
        $arr = array();
        $arr['ticket'] = $ticket;
        $arr['nonceStr'] = $nonceStr;
        $arr['timeStamp'] = $timeStamp;
        $arr['url'] = $url;
        $arr['signature'] = $signature;
        return $config = array(
            'url' => $url,
            'nonceStr' => $nonceStr,
            'agentId' => $agentId,
            'timeStamp' => $timeStamp,
            'corpId' => $corpId,
            'signature' => $signature);
    }
    /**
     * @param $accessToken
     * @param $code
     * @return 个人授权信息
     */
    public function getPerson($accessToken, $code)
    {
        $response = $this->http->get("/user/get_private_info",
            array("access_token" => $accessToken, "tmp_auth_code" => $code));
        return json_encode($response);
    }
    protected function sign($ticket, $nonceStr, $timeStamp, $url)
    {
        $plain = 'jsapi_ticket=' . $ticket .
            '&noncestr=' . $nonceStr .
            '&timestamp=' . $timeStamp .
            '&url=' . $url;
        return sha1($plain);
    }
    function curPageURL()
    {
        $pageURL = 'http';
        if (array_key_exists('HTTPS',$_SERVER)&&$_SERVER["HTTPS"] == "on")
        {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        }
        else
        {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

    public function sendNotice($data,$all,$userid)
    {
        $this->initialize();
//        $data = $this->request->param("base");
//        $all = $this->request->param("all");
        require_once("../vendor/dingding/TopSdk.php");
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET , \DingTalkConstant::$FORMAT_JSON);
        if ($this->access_token) {
            $time = date("Y-m-d H:i:s");
            //$userid = session("dd_userid");
            $title = $data['title'];
            $subtitle = "###### " .$data['subtitle'];
            $url = urlencode($data['url']);
            $single_url = "dingtalk://dingtalkclient/page/link?url=" .$url  . "&pc_slide=true";
            $pic = " [![](" .$data['picurl'] . ")](" . $single_url .")";
            $mdstr = "# " .$title . " \n " . $subtitle ." \n " . $pic . " \n " .$time;
            $single_title = "查看详情";

            $carddata = array("title"=>$title,"markdown"=>$mdstr,"single_title"=>$single_title,"single_url"=>$single_url);
            $msgdata = array("msgtype"=>"action_card","action_card"=>$carddata);
            $msg = json_encode($msgdata);
            $req = new \OapiMessageCorpconversationAsyncsendV2Request;

            $req->setAgentId($this->agentid);
            $req->setUseridList($userid);

            //$toalluser = true;
            if($all == "1") $req->setToAllUser('true');//$req->setUseridList($userid);

            $req->setMsg($msg);
            $resp = $c->execute($req,$this->access_token,"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            //print_r($resp);
            if($resp->errcode =='0') return json_encode(["code"=>1,"msg"=>"发送成功"]);//$this->success('发送成功！');
            else return json_encode(["code"=>0,"msg"=>"发送失败"]);//$this->error('发送失败！');
        }
    }

    public function get_process(){
        $this->initialize();
        require_once("../vendor/dingding/TopSdk.php");
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET , \DingTalkConstant::$FORMAT_JSON);
        $access_token = $this->access_token;
        if ($access_token) {
            //$userid = session("dd_userid");
            $req = new \OapiProcessinstanceListidsRequest;
            $req->setProcessCode('PROC-0D131122-95EB-4308-ABE2-0D0ED984A041');
            $req->setStartTime(time()-86400);

            $resp = $c->execute($req,$access_token,"https://oapi.dingtalk.com/topapi/processinstance/listids");
            return $resp;//print_r($resp);
        }
    }

    public function get_process_detail($id){

        $this->initialize();
        require_once("../vendor/dingding/TopSdk.php");
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET , \DingTalkConstant::$FORMAT_JSON);
        $access_token = $this->access_token;
        if ($access_token) {
            $req = new \OapiProcessinstanceGetRequest;
            $req->setProcessInstanceId($id);

            $resp = $c->execute($req,$access_token,"https://oapi.dingtalk.com/topapi/processinstance/get");
cmf_log(json_encode($resp));
            return $resp;//print_r($resp);

        }
    }

    public function callback_reg($url,$cbtag){
        $this->initialize();
        require_once("../vendor/dingding/TopSdk.php");
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET , \DingTalkConstant::$FORMAT_JSON);
        $access_token = $this->access_token;
        if ($access_token) {
            $req = new \OapiCallBackGetCallBackRequest();
            $resp = $c->execute($req,$access_token,"https://oapi.dingtalk.com/call_back/get_call_back");
            if($resp->errcode == '71007'){
                $c1 = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_POST , \DingTalkConstant::$FORMAT_JSON);
                $req1 = new \OapiCallBackRegisterCallBackRequest();
                $req1->setUrl($url);
                $aeskey = '1234567890123456789012345678901234567890123';
                $req1->setAesKey($aeskey);
                $token = '123456';
                $req1->setToken($token);
                $callbacktag = json_encode($cbtag);
                $req1->setCallBackTag($callbacktag);
                $resp = $c1->execute($req1,$access_token,"https://oapi.dingtalk.com/call_back/register_call_back");
            }
            else{
                $c1 = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_POST , \DingTalkConstant::$FORMAT_JSON);
                $req1 = new \OapiCallBackUpdateCallBackRequest();
                $req1->setUrl($url);
                $aeskey = '1234567890123456789012345678901234567890123';
                $req1->setAesKey($aeskey);
                $token = '123456';
                $req1->setToken($token);
                $callbacktag = json_encode($cbtag);
                $req1->setCallBackTag($callbacktag);
                $resp = $c1->execute($req1,$access_token,"https://oapi.dingtalk.com/call_back/update_call_back");
            }
            return $resp;//print_r($resp);
        }
    }

    public function get_user($userid){
        $this->initialize();
        require_once("../vendor/dingding/TopSdk.php");
        $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET , \DingTalkConstant::$FORMAT_JSON);
        $access_token = $this->access_token;
        if ($access_token) {
            $req = new \OapiUserGetRequest();
            $req->setUserid($userid);
            $resp = $c->execute($req, $access_token, "https://oapi.dingtalk.com/user/get");
            if($resp){
                if($resp->errcode == '0'){
                    return ['username'=>$resp->name,'mobile'=>$resp->mobile];
                }
            }

        }
        return;
    }
}